/**
 * 案例：通过AST的操作，修改项目配置文件
 */
const fs = require('fs');
const path = require('path');
const acorn = require('acorn');
const { print } = require('recast');

// 读取源配置文件
const srcFilePath = path.join(__dirname, 'src/config.js');
const srcFileContent = fs.readFileSync(srcFilePath, 'utf-8');
const outputFilePath = path.join(__dirname, 'dist/config.js');
const originAST = acorn.parse(srcFileContent, {
    ecmaVersion: 'latest',
    sourceType: 'module',
});
const exportAST = originAST.body.filter((obj) => obj.type === 'ExportDefaultDeclaration');
const exportDeclaration = exportAST[0].declaration;
if(exportDeclaration.type === 'Identifier'){
    const exportVar = originAST.body.filter((obj) => obj.type === 'VariableDeclaration' && obj.declarations[0].id.name === exportDeclaration.name)[0];
    if(exportVar.declarations[0].init.type === 'ObjectExpression'){
        exportVar.declarations[0].init.properties.forEach((propertyItem) => {
            if(propertyItem.key.name === 'ssr'){
                propertyItem.value = {
                    "type": "Literal",
                    "value": true,
                    "raw": "true"
                };
            }
        });
    }
}
const outputConent = `// 本代码由工程脚本修改完成 \n ${print(originAST).code}`;;
fs.writeFileSync(outputFilePath, outputConent);
